import axios from 'axios'
import { Toast } from 'vant';
import router from "@/router/index.js";
import { Base64 } from "js-base64"
import 'vant/es/toast/style';
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 50000
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const userinfo = localStorage.getItem('userinfo')
        if (userinfo) {
            const token = Base64.encode(JSON.parse(userinfo).token + ":");
            config.headers.Authorization = `Basic ${token}`
        }
        // if (store.getters.token) {
        //   // 如果token存在 注入token
        //   config.headers.Authorization = `Bearer ${store.getters.token}`
        // }
        return config // 必须返回配置
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const { code, msg, data } = response.data
        //   要根据success的成功与否决定下面的操作
        if (code == 200) {
            return data ? data : response.data
        } else {
            const isStr = Object.prototype.toString.call(msg)
            Toast.fail(isStr == '[object String]' ? msg : msg[0]);

            // TODO：业务错误
            return Promise.reject(new Error(msg))
        }
    },
    (error) => {

        // 处理 token 超时问题
        if (error.response && error.response.data) {
            console.log('error.response :>> ', error.response.data.msg);
            const msg = error.response.data.msg
            const isStr = Object.prototype.toString.call(msg)
            Toast.fail(isStr == '[object String]' ? msg : msg[0]);
            const { error_code } = error.response.data
            if (error_code == 10000) {
                localStorage.removeItem("userinfo");
                setTimeout(() => {
                    router.push("/login");
                }, 1000);
            }
        }

        // $message('error', error.response.data.message)
        // TODO: 提示错误消息
        return Promise.reject(error)
    }
)

export default service
